"""
@File    : JiraHelper.py
@Time    : 2019/12/13 14:32
@Author  : LiuFeiYu
@Email   : Liufeiyu@sunrise.net
@Software: PyCharm
"""
import base64
import jira
from matplotlib import pyplot as plt
from pandas import value_counts
from Common.ResponseHelper import GetKey
from Common.RequestsHelper import Request
from Script.JiraScript import *
from Script.JenkinsScript import *
from ProjectEnum import *


class GetJiraData:
    def __init__(self):
        self._jr_url = jira_connect_url  # jira地址
        self._jr_username = jira_username  # jira用户名
        self._jr_password = jira_password  # 密码
        self.jr_server = jira.JIRA(basic_auth=(self._jr_username, self._jr_password),
                                   options={"server": self._jr_url})

    def get_all_issue_key_done(self, project_key):
        all_issue = self.jr_server.search_issues(
            jql_str=f"project = {project_key} AND issuetype = Bug AND status = Done",
            maxResults=100000
        )
        new_dict = list()
        for i in all_issue:
            new_dict.append(i.key)
        return new_dict

    @staticmethod
    def get_plb_name(title_name):
        return get_plb_title_name(title_name)

    @staticmethod
    def get_picture_name(title_name):
        return get_save_picture_name(title_name)

    def get_project_assignee_bug_num(self, title_name, issue_keys: list):
        picture_name = self.get_picture_name(title_name)
        title_name = self.get_plb_name(title_name)
        new_author = list()
        plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
        plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
        x = []
        y = []
        for issue_key in issue_keys:
            author_res = self.get_issue_true_assignee(issue_key)
            new_author.append(get_issue_assignee(author_res))
        res = value_counts(new_author)
        for i in list(res.items()):
            x.append(f"{i[0]}[{i[1]}]")
            y.append(i[1])
        plt.bar(x, y, align='center')
        plt.title(f'{title_name} BUG统计')
        plt.ylabel('BUG数量')
        plt.xlabel('人员名字')
        plt.savefig(f'{picture_name}.jpg')
        plt.show()

    def get_issue_true_assignee(self, issue_key, data_num=-1):
        """获取问题单真实经办人"""
        global author
        # 获取问题单
        get_issue = self.jr_server.issue(issue_key)
        # 获取问题单经办人
        assignee_name = get_issue.fields.assignee.name
        # 获取问题单创建人
        creator = get_issue.fields.creator.name

        if assignee_name != creator:
            author = assignee_name
        else:
            # base64加密账号密码以登录jira
            str_demo = "liufeiyu92:123456"
            str_demo = str_demo.encode('utf-8')
            new = str(base64.b64encode(str_demo), encoding='utf-8')
            url = f"http://192.168.10.216:8200/rest/api/2/issue/{issue_key}?expand=changelog&fields=summary"
            res = Request.get_request(url=url,
                                      headers={
                                          "Authorization": f"Basic {new}"
                                      })
            get_num = GetKey.get_keys(res.get('body'), 'changelog', 'total')
            change_log = GetKey.get_keys(res.get('body'), 'changelog', 'histories')[data_num]  # list
            to_author = GetKey.get_keys(change_log, 'items', 'to')
            from_author = GetKey.get_keys(change_log, 'items', 'from')
            if isinstance(to_author, list) or isinstance(from_author, list):
                if abs(data_num) != get_num:
                    self.get_issue_true_assignee(issue_key, data_num=data_num - 1)
            else:
                assert_1 = to_author != from_author
                assert_2 = (to_author == creator) or (from_author == creator)
                bool_check = (assert_1
                              and assert_2)
                # 递归查询到最后一次指派给创建问题单的用户
                if bool_check:
                    author = from_author if to_author == creator else to_author
                else:
                    self.get_issue_true_assignee(issue_key, data_num=data_num - 1)
        return author

    def all_project(self):
        """登录用户所有项目"""
        return self.jr_server.projects()

    def search_user(self, user_name):
        """搜索用户"""
        return self.jr_server.search_users(user_name)

    def get_issue_status(self, issue_obj):
        """回去issue工作流状态"""
        # 获取BUG可流转状态
        transitions = self.jr_server.transitions(issue_obj)
        issue_transitions = [(t['id'], t['name']) for t in transitions]
        return issue_transitions

    def create_issue(self, project_id, summary, description, assignee, priority="3", issuetype="10004"):
        """
        创建问题单
        :param project_id: 项目id
        :param summary: 问题单主题
        :param description: 问题单描述
        :param assignee: 经办人(问题指派人)
        :param issuetype: 问题类型,默认10004(故障)
        :param priority:问题优先级
        :return:问题单ID
        """
        # 判断是否已经存在已经提交此问题，状态为未完成
        issue_check = self.jr_server.search_issues(
            jql_str=f'status in ("In Progress", "To Do") AND text ~ "{summary}"',
            maxResults=100000)
        # 如果存在则跳过提交问题
        if len(issue_check) > 0:
            return issue_check
        else:
            # 如果不存在，则判断是否已经存在同一个问题，状态为已完成
            issue_done = self.jr_server.search_issues(
                jql_str=f'status = Done AND text ~ "{summary}"',
                maxResults=100000
            )
            if len(issue_done) > 0:
                my_issue = self.jr_server.issue(issue_done[0])
                # 如果存在，更改BUG单状态为处理中
                self.jr_server.transition_issue(my_issue, JiraIssueEnum.IssueStatus.value)
                # 同时更新BUG经办人和allure报告地址
                issue_dict = {
                    "description": description
                }
                my_issue.update(assignee={'name': assignee}, fields=issue_dict)
                return my_issue
            else:
                # 否则提交新问题单
                field = {
                    'project': {'id': project_id},  # 项目
                    'issuetype': {'id': issuetype},  # 问题类型
                    'priority': {'id': priority},  # 优先级 1High, 2Highest, 3Medium, 4Low, 5Lowest
                    'summary': summary,  # 问题主题
                    'assignee': {'name': assignee},  # 经办人
                    'description': description  # 问题描述
                    # 'customfield_11901': test_svn, # 测试版本SVN号
                    # 'customfield_10002': test_env, # 测试环境
                    # 'fixVersions': [{'name': fix_version}],  # 修复版本
                    # 'versions': [{'name': versions}],  # 影响版本
                    # 'components': [{'name': component}],  # 相关模块
                    # 'customfield_12223': [labels],  # 功能标签
                }
                return self.jr_server.create_issue(fields=field)

    @staticmethod
    def summary_format(module_name):
        """jira问题单主题格式"""
        return f"【后端】【接口问题】{module_name}"

    @staticmethod
    def description_format():
        """jira问题单描述格式"""
        des_format = "[" + jenkins_allure_report_url + "]"
        return des_format


if __name__ == '__main__':
    # _jr_url = jira_connect_url  # jira地址
    # _jr_username = jira_username  # jira用户名
    # _jr_password = jira_password  # 密码
    # jr_server = jira.JIRA(server=_jr_url,
    #                       basic_auth=(_jr_username, _jr_password))

    jr = GetJiraData()
    # print(jr.all_project())
    print(jr.description_format())
    # print(jr.get_issue_true_assignee(issue_key="JZW-298"))
    # list_data = jr.get_all_issue_key_done("LYJTGL")
    # jr.get_project_assignee_bug_num('LYJTGL', list_data)
    # print(jr.get_issue_true_assignee("LYJTGL-107"))

    # print(search_user(jr_server, '刘银'))
    # print(all_project(jr_server))
    # order by created DESC
    # 查看问题单活动记录
    # http://192.168.10.216:8200/rest/api/2/issue/LYJTGL-123?expand=changelog&fields=summary
    # project = '智慧洪雅智慧旅游停车管理平台" AND issuetype = "10004" AND status = Done'
    # demo = jr_server.search_issues(
    #     jql_str='status = Done AND text ~ "【后端】【接口问题】"',
    #     maxResults=100000)
    # issue = jr_server.issue(demo[0])
    # issue_status = jr_server.transitions(issue)
    # status = [(t['id'], t['name']) for t in issue_status]
    # print(status)
    # print(jr_server.transition_issue(issue, "21"))
    pass
